<template>
	<view>
		<view id="vs"></view>
		<view>
			<u-cell-group :border="showBorder">
				<u-cell :border="showBorder" :isLink="true" style="font-size: 10px;margin-top: 10px;" value="简介"
					@click="jjshow=true">
					<view slot="title" class="u-slot-title">
						<view style="font-size: 16px">
							{{vodInfo.vodName}}
						</view>
					</view>
				</u-cell>
				<u-cell :border="showBorder" style="margin-top: 0px;">
					<view slot="title" class="u-slot-title">
						<u-scroll-list :indicator="indicator">
							<view class="score"> {{vodInfo.vodScore}}分 </view>
							<view class="area">| {{vodInfo.vodArea}} {{vodInfo.vodLang}} | {{vodInfo.vodYear}}
							</view>
						</u-scroll-list>
					</view>
				</u-cell>

				<view style="margin: 0px 0px 5px 15px;display: flex;flex-direction: row;align-items: center;">
					<u-col span="9" style="display: flex;flex-direction: row;align-items: center;">
						<view class="xuanji">播放源</view>
						<view style="color: #757575;font-size: 13px;">(如不能播放请切换播放源)</view>
					</u-col>
					<u-col span="3">
						<view style="margin-right: 15px;">
							<u-button text="下载" size="small"
								color="linear-gradient(to right, rgb(26, 183, 255), rgb(213, 51, 186))"></u-button>
						</view>
					</u-col>
				</view>
				<view>
					<u-scroll-list :indicator="false" style="margin-top: 5px;margin-left: 15px;">
						<view v-for="(item, index) in vodInfo.vodPlayFromName" :key="index"
							style="margin-right: 10px;font-size: 14px;color: #FFFFFF;">
							<view class="btn" @click="changePlayFrom(item,index)" style="border: solid 1px #00AAFF;border-radius: 3px;width: 70px;"
								:style="{backgroundColor:index != activeIndex1?'transparent':'#3c9cff',background:index != activeIndex1?'transparent':'#3c9cff'}">
								<text style="font-size:12px;padding:5px"
									:style="{color:index != activeIndex1?'#757575':'#FFFFFF'}">{{item}}</text>
							</view>
						</view>
					</u-scroll-list>
				</view>
				<u-line></u-line>

				<u-cell :border="showBorder" :isLink="true" :value="vodInfo.vodRemarks" @click="xjshow = true">
					<view slot="title" class="u-slot-title">
						<view class="xuanji">选集</view>
					</view>
				</u-cell>
				<view style="margin-left: 15px; margin-right: 10px;">
					<u-scroll-list :indicator="indicator" v-if="refreshXj">
						<view v-for="(item, index) in xuanJiList" :key="index" style="margin-right: 10px;">
							<u-button type="primary" style="min-width: 45px;" :plain="activeIndex != index"
								:text="item.name" @click="toChangeSrc(index)">
							</u-button>
						</view>
					</u-scroll-list>
				</view>				
				<view style="margin: 0px 0px 5px 10px;display: flex;flex-direction: row;align-items: center;">
					<u-col span="9" style="display: flex;flex-direction: row;align-items: center;">
						<view style="font-size: 18px;font-weight: 700;">猜你喜欢</view>
					</u-col>
					<u-col span="3">
						<view style="margin-right: 10px;">
							<u-button text="换一批" size="small" shape="circle" @click="findGuessVodPage"></u-button>
						</view>
					</u-col>
				</view>
				<view style="margin-left: 10px; margin-right: 10px;">
					<u-scroll-list :indicator="indicator">
						<view v-for="(item, idx) in vodGuessList" :key="idx" style="margin-right: 10px;">
							<view class="vod" @click="toDetail(item)">
								<image class="cover" :src="item.vodPic"></image>
								<view class="renew">{{item.vodRemarks}}</view>
								<view class="title">{{item.vodName}}</view>
							</view>
						</view>
					</u-scroll-list>
				</view>

			</u-cell-group>


			<u-popup v-if="jjshow" :show="true" mode="bottom">
				<view :style="{ height: `${popupHeight}px` } ">
					<u-cell-group :border="showBorder">
						<u-cell :isLink="true" style="font-size: 10px;margin-top: 10px;" arrowDirection="down"
							@click="closejj">
							<view slot="title" class="u-slot-title">
								<view style="font-size: 16px">{{vodInfo.vodName}}</view>
							</view>
						</u-cell>
						<u-cell :border="showBorder" style="margin-top: 10px;">
							<view slot="title" class="u-slot-title">
								<view style="font-size: 13px;">导演：{{vodInfo.vodDirector}}</view>
							</view>
						</u-cell>
						<u-cell :border="showBorder" style="margin-top: 5px;">
							<view slot="title" class="u-slot-title">
								<view style="font-size: 13px;">主演：{{vodInfo.vodActor}}</view>
							</view>

						</u-cell>
						<u-cell :border="showBorder" style="margin-top: 5px;">
							<view slot="title" class="u-slot-title">
								<view style="font-size: 13px;" v-if="vodInfo.vodPubdate">上映时间：{{vodInfo.vodPubdate}}
								</view>
								<view style="font-size: 13px;" v-else>上映时间：{{vodInfo.vodYear}}</view>
							</view>
						</u-cell>
						<u-cell :border="showBorder" style="margin-top: 20px;">
							<view slot="title" class="u-slot-title">
								<view style="font-size: 16px;">简介</view>
							</view>
						</u-cell>
						<u-cell :border="showBorder" style="margin-top: 5px;">
							<view slot="title" class="u-slot-title">
								<view style="font-size: 13px;line-height: 15px;">{{vodInfo.vodContent}}</view>
							</view>
						</u-cell>
					</u-cell-group>
				</view>
			</u-popup>
			<u-popup v-if="xjshow" :show="true" mode="bottom">
				<view :style="{ height: `${popupHeight}px` } ">
					<u-cell :isLink="true" style="font-size: 10px;margin-top: 10px;" arrowDirection="down"
						@click="closexj">
						<view slot="title" class="u-slot-title">
							<view>选集</view>
						</view>
					</u-cell>
					<view :style="{ maxHeight: `${popupHeight - 50}px` } "
						style="padding: 10px; display: flex;  flex-wrap: wrap;overflow:auto">
						<view v-for="(item, index) in xuanJiList" :key="index" style="margin: 5px;">
							<u-button type="primary" :plain="activeIndex != index"
								style="margin-bottom:5px;min-width: 45px;" :text="item.name"
								@click="toChangeSrc(index)">
							</u-button>
						</view>
					</view>
				</view>
			</u-popup>
		</view>
	</view>

</template>

<script type="text/ecmascript-6">
	import {
		getVodDetail,
		getVodRecommend
	} from '../../config/api.js';
	// #ifdef H5
	import Player from 'xgplayer';
	import playbackRate from 'xgplayer/dist/controls/playbackRate';
	import HlsJsPlayer from 'xgplayer-hls.js';
	// #endif
	export default {
		props: {
			vodId: 0,
		},
		data() {
			return {
				isLoadPage: true,
				activeIndex1: 0,
				activeIndex: 0,
				barHeight: 25, //动态高度初始值
				typecolumn: 5,
				xjshow: false,
				jjshow: false,
				refreshXj: true,
				showBorder: false,
				indicator: false,
				episode: 0,
				srcList: [],
				gDuration: 0, //大概总时长
				videoList: [],
				downloadList: [],
				index: 1, //当前集数
				initialTime: 0,
				fullScreen: false,
				platform: '',
				vodInfo: "",
				xuanJiList: [{
					"name": ''
				}],
				src: '',
				pic: '',
				vodGuessList: [],
				canBack: false,
				popupHeight: uni.getSystemInfoSync().windowHeight - 230,
				player: null

			}
		},
		async mounted() {
			debugger
			await this.findVodDetail(this.vodId)
			this.initCacheVodInfo()
			
			this.pic = this.vodInfo.vodPic
			var that = this
			console.log(that.srcList[that.activeIndex].src)
			that.player = new HlsJsPlayer({
				id: "vs",
				url: that.srcList[that.activeIndex].src,
				autoplay: true,
				playbackRate: [1.0, 1.5, 2.0, 2.5, 3.0] //传入倍速可选数组
			})
			that.player.once('ready',()=>{
				that.player.play()
			})
			this.findGuessVodPage();

		},
		onBackPress() {
			this.cacheLocalHistory()
		},
		onHide() {
			this.cacheLocalHistory()		
		},
		beforeDestroy() {
			console.log('beforeDestroy')
			this.cacheLocalHistory()	
			// this.player.destroy(false);
			// this.player=null
		},
		methods: {
			sortByKey(propertyName) {
				return function sortList(object1, object2) {
					const value1 = object1[propertyName];
					const value2 = object2[propertyName];
					if (value2 < value1) {
						return 1;
					}
					if (value2 > value1 && value2.length > value1.length) {
						return -1;
					}
					return 0;
				};
			},
			parseVodInfo() {
				let playArr = this.vodInfo.vodPlayUrlList[this.activeIndex1].split("#");
				let xjList = [];
				let srcArr = [];
				playArr.forEach((item) => {
					let playInfo = item.split("$");
					let obj = {
						"title": "高清",
						"src": playInfo[1],
						"name": playInfo[0].replace("第", "").replace("集", "")
					}
					let obj2 = {
						"name": playInfo[0].replace("第", "").replace("集", "")
							.replace("p", ""),
						"src": playInfo[1]
					}
					if (playInfo[1].endsWith('m3u8')) {
						xjList.push(obj2);
						srcArr.push(obj);
					}
				})
				this.xuanJiList = xjList.sort(this.sortByKey('name'));
				this.srcList = srcArr.sort(this.sortByKey('name'));
				let vod = {
					"srcList": this.srcList,
					"danmuList": [],
					"title": this.vodInfo.vodName,
					"download": false,
					"episode": this.srcList.length,
					"poster": this.vodInfo.vodPic
				}
				this.episode = this.srcList.length;
				this.videoList.push(vod);
			},
			async findVodDetail(vodId) {
				var that = this
				// get请求
				await getVodDetail("?vodId=" + vodId).then((res) => {
					that.vodInfo = res;
					getVodRecommend("?typeId=" + that.vodInfo.typeId + "&t=" + new Date().getTime()).then((
						res) => {
						console.log(res)
						that.vodGuessList = res
					})
					console.log(res)
					if (res) {
						let playArr = res.vodPlayUrlList[this.activeIndex1].split("#");
						let xjList = [];
						let srcArr = [];
						playArr.forEach((item) => {
							let playInfo = item.split("$");
							let obj = {
								"title": "高清",
								"src": playInfo[1],
								"name": playInfo[0].replace("第", "").replace("集", "")
									.replace("p", ""),
							}
							let obj2 = {
								"name": playInfo[0].replace("第", "").replace("集", "")
									.replace("p", ""),
								"src": playInfo[1]
							}
							if (playInfo[1].endsWith('m3u8')) {
								xjList.push(obj2);
								srcArr.push(obj);
							}

						})
						that.xuanJiList = xjList.sort(that.sortByKey('name'));
						that.srcList = srcArr.sort(that.sortByKey('name'));
						console.log("333333333333333" + that.srcList[0])

						let vod = {
							"srcList": that.srcList,
							"danmuList": [],
							"title": res.vodName,
							"initialTime": 0,
							"gDuration": 0, //大概总时长
							"download": false,
							"episode": that.srcList.length,
							"poster": res.vodPic
						}
						that.episode = that.srcList.length;
						that.videoList.push(vod);
						that.initypeColumn()

					}
				})
			},
			//猜你喜欢
			findGuessVodPage() {
				var that = this
				getVodRecommend("?typeId=" + that.vodInfo.typeId + "&t=" + new Date().getTime()).then((res) => {
					console.log(res)
					that.vodGuessList = res
				})
				
			},
			toChangeSrc(idx) {				
				var that = this
				that.index = idx + 1;
				that.activeIndex = idx;
				that.initialTime = 0;
				that.src = that.srcList[that.activeIndex].src
				if (that.player) {
					that.player.src = that.src
					that.player.play()
				} else {
					that.player = new HlsJsPlayer({
						id: "vs",
						url: that.src,
						autoplay: true,
						playbackRate: [1.0, 1.5, 2.0, 2.5, 3.0] //传入倍速可选数组
					})
					that.player.on('complete', () => {
						console.log('complete2')

					})
					that.player.on('play', () => {
						console.log('play')
					})
					that.player.on('destroy', () => {
						console.log('player', 'destroy')
					})
				}

			},

			toDetail(item) {
				uni.$u.route({
					url: 'pages/dplayer/dplayer',
					params: {
						vodId: item.vodId
					}
				})
			},
			openjj() {
				this.jjshow = true;
				// console.log('open');
			},
			closejj() {
				uni.$u.debounce(this.jjshow = false, 500)
				// console.log('close');
			},
			initypeColumn() {
				if (this.vodInfo.typePid == 1) {
					this.typecolumn = 4;
				}
				if (this.vodInfo.typePid == 2) {
					this.typecolumn = 5;
				}
				if (this.vodInfo.typePid == 3) {
					this.typecolumn = 3;
				}
				if (this.vodInfo.typePid == 4) {
					this.typecolumn = 5;
				}
			},
			openxj() {
				console.log(this.vodInfo.typePid)
				this.xjshow = true;
				// console.log('open');
			},
			closexj() {
				this.xjshow = false
				// console.log('close');
			},
			message(event) {
				console.log('接收到消息', event.detail.data)
				this.gDuration = Math.floor(event.detail.data[0].gDuration)
				this.initialTime = Math.floor(event.detail.data[0].initialTime)
				console.log('接收到消息', this.gDuration)

				this.cacheLocalHistory()

			},
			cacheLocalHistory() {
				console.log('接收到消息', this.gDuration)
				try {
					var that = this
					let videoStorage = uni.getStorageSync('videoHistory')
					// 判断缓存中是否存在此视频
					console.log('videoHistory', JSON.stringify(videoStorage))
					if (!videoStorage) {
						videoStorage = [];
					}
					const idx = videoStorage.findIndex(item => item.vodId == this.vodInfo.vodId);
					console.log(idx)
					if (idx === -1) {

						if (that.player.duration && that.player.duration > 0) {
							let obj = {
								'vodId': that.vodInfo.vodId, //视频唯一标识
								'gDuration': that.player.duration,
								'timeStorage': that.player.currentTime, //用户返回时保存的时间
								'vodPic': that.vodInfo.vodPic,
								'vodName': that.vodInfo.vodName,
								'currentIndex': that.index,
								'spareTime': that.player.duration - that.player.currentTime, //剩余时长
								'seriesName': that.xuanJiList[that.activeIndex].name
							}
							console.log("视频缓存第几集索引:" + obj.currentIndex)

							videoStorage.unshift(obj)
							uni.setStorage({
								key: 'videoHistory',
								data: videoStorage,
								success: function() {
									console.log('success')
								}
							})
						}

					} else { //缓存中已有相同视频，改变已看时间替换缓存
						if (that.player.duration && that.player.duration > 0) {
							videoStorage[idx].gDuration = that.player.duration
							videoStorage[idx].timeStorage = that.player.currentTime
							videoStorage[idx].currentIndex = that.index;
							videoStorage[idx].spareTime = that.player.duration - that.player.currentTime;
							videoStorage[idx].seriesName = that.xuanJiList[that.activeIndex].name

							uni.setStorage({
								key: 'videoHistory',
								data: videoStorage
							})
						}

					}
				} catch (error) {
					console.log('缓存失败', error)
				}
			},
			initCacheVodInfo() {
				debugger
				var that = this
				try {
					this.videoStorage = uni.getStorageSync('videoHistory')
					if (this.videoStorage) {
						console.log('videoHistory', JSON.stringify(this.videoStorage))
						const videoArr = this.videoStorage
						console.log(this.vodId)
						const idx = videoArr.findIndex(item => item.vodId == this.vodInfo.vodId);
						if (idx != -1) {
							let vod = videoArr[idx];
							console.log('视频时长', vod.gDuration)
							that.index = Number(vod.currentIndex);
							const initialTime = Number(vod.timeStorage);
							console.log('initialTime===>', initialTime)
							that.activeIndex = that.index - 1;
							that.player.currentTime = initialTime;
							that.src = that.srcList[that.index].src

						} else {
							console.log('没找到')
						}
					}
				} catch (error) {
					console.log('error', error)
				}
			},
			changePlayFrom(item, index) {
				console.log(item)
				this.activeIndex1 = index
				this.parseVodInfo();
				console.log(this.xuanJiList)
				this.refreshXj = false
				setTimeout(() => {
					this.refreshXj = true
				}, 10);
			}
		}
	}
</script>

<style scoped lang="scss">
	.statbar {
		height: var(--status-bar-height);
	}

	.content {
		width: 750rpx;
		align-items: center;
	}


	.score {
		color: #00aaff;
		font-size: 14px;
	}

	.area {
		color: #808080;
		font-size: 14px;
	}

	.xuanji {
		font-size: 16px;
	}

	.vod {
		width: 110px;
		height: 175px;
	}

	.cover {
		width: 110px;
		height: 150px;
		border-radius: 5px;
		position: relative;
	}

	.renew {
		position: relative;
		color: #FFFFFF;
		font-size: 10px;
		top: -20px;
		text-align: right;
		right: 10px;
	}

	.title {
		position: relative;
		padding-left: 5px;
		padding-right: 5px;
		font-size: 14px;
		top: -10px;
		width: 110px;
		overflow: hidden;
		text-overflow: ellipsis;
		lines: 1;
	}

	.btn {
		line-height: 25px;
		color: #FFFFFF;
		font-size: 12px;
		min-width: 50px;
		text-align: center;
		vertical-align: middle;
		padding-left: 5px;
		padding-right: 5px;
	}

	#vs {
		width: 100% !important;
		height: 230px !important;
	}

	/deep/ .xgplayer-skin-default .xgplayer-enter .xgplayer-enter-spinner {
		display: block;
		position: absolute;
		left: 50%;
		top: 50%;
		height: 50px;
		width: 50px;
		position: relative;
		-webkit-transform: translate(-50%, -50%);
		-ms-transform: translate(-50%, -50%);
		transform: translate(-50%, -50%);
	}

	/deep/ .u-cell__body {
		display: flex;
		flex-direction: row;
		box-sizing: border-box;
		padding: 5px 15px;
		font-size: 15px;
		color: #303133;
		align-items: center;
	}
	/deep/ .u-button--small {
		min-width: 60px;
		height: 28px;
		padding: 0px 10px;
		font-size: 12px;
	}
</style>
